package com.yj.algorithm

import android.util.Log
class algorithm1 {
    companion object {
        private val instance = algorithm1()

        /**
         * 获取单例
         */
        fun getInstance() = instance
    }


    //罗马数字变成十进制数字
    fun decode1(str: String): Int {
        val tmp = str.map {
            when (it) {
                'M' -> 1000
                'D' -> 500
                'C' -> 100
                'L' -> 50
                'X' -> 10
                'V' -> 5
                else -> 1
            }
        }
        return tmp.mapIndexed { index, i -> if (tmp.size > (index + 1) && i < tmp[index + 1]) -i else i }
                .sum()
    }

    //把罗马数字转换为阿拉伯数字
    fun decode2(m: String): Int {
        val graph = IntArray(400)
        graph['I'.toInt()] = 1
        graph['V'.toInt()] = 5
        graph['X'.toInt()] = 10
        graph['L'.toInt()] = 50
        graph['C'.toInt()] = 100
        graph['D'.toInt()] = 500
        graph['M'.toInt()] = 1000
        val num = m.toCharArray()
        var sum = graph[num[0].toInt()]
        for (i in 0 until num.size - 1) {
            if (graph[num[i].toInt()] >= graph[num[i + 1].toInt()]) {
                sum += graph[num[i + 1].toInt()]
            } else {
                sum = sum + graph[num[i + 1].toInt()] - 2 * graph[num[i].toInt()]
            }
        }
        Log.e("sum", sum.toString())
        return sum
    }

    //我的解决方案
    fun decodeMy(str: String): Int {
        val strArray = str.split("")
        var intArray = emptyList<Int>().toMutableList()
        strArray.forEachIndexed { _, s ->
            var mm = 0
            when (s) {
                "M" -> mm = 1000
                "D" -> mm = 500
                "C" -> mm = 100
                "L" -> mm = 50
                "X" -> mm = 10
                "V" -> mm = 5
                "I" -> mm = 1
            }
            intArray.add(mm)
        }
        var numStr = intArray[0]
        for (i in 0 until intArray.size - 1) {
            if (intArray[i] >= intArray[i + 1]) {
                numStr += intArray[i + 1]
            } else {
                numStr = numStr + intArray[i + 1] - 2 * intArray[i]
            }
        }
        Log.e("numStr", numStr.toString())
        return numStr
    }
}